import React, { useRef, useEffect, useCallback } from 'react';
import { Editor } from '@monaco-editor/react';
import { Card, Button, Space, Tooltip } from 'antd';
import { 
  FormatPainterOutlined, 
  FullscreenOutlined, 
  SettingOutlined,
  BugOutlined,
  CheckCircleOutlined
} from '@ant-design/icons';
import * as monaco from 'monaco-editor';
import { EditorMarker } from '../../types/analysis';

interface SqlEditorProps {
  value: string;
  onChange: (value: string) => void;
  height?: number;
  language?: string;
  theme?: string;
  readOnly?: boolean;
  options?: any;
  markers?: EditorMarker[];
  onMarkerClick?: (marker: EditorMarker) => void;
  onCursorPositionChange?: (line: number, column: number) => void;
  showLineNumbers?: boolean;
  enableFormatting?: boolean;
  onFormat?: () => void;
}

const SqlEditor: React.FC<SqlEditorProps> = ({
  value,
  onChange,
  height = 400,
  language = 'sql',
  theme = 'vs-light',
  readOnly = false,
  options = {},
  markers = [],
  onMarkerClick,
  onCursorPositionChange,
  showLineNumbers = true,
  enableFormatting = true,
  onFormat
}) => {
  const editorRef = useRef<monaco.editor.IStandaloneCodeEditor | null>(null);
  const monacoRef = useRef<typeof monaco | null>(null);

  // 处理编辑器挂载
  const handleEditorDidMount = useCallback((editor: monaco.editor.IStandaloneCodeEditor, monacoInstance: typeof monaco) => {
    editorRef.current = editor;
    monacoRef.current = monacoInstance;

    // 监听光标位置变化
    if (onCursorPositionChange) {
      editor.onDidChangeCursorPosition((e) => {
        onCursorPositionChange(e.position.lineNumber, e.position.column);
      });
    }

    // 监听标记点击
    if (onMarkerClick) {
      editor.onMouseDown((e) => {
        const position = e.target.position;
        if (position && markers.length > 0) {
          const clickedMarker = markers.find(marker => 
            position.lineNumber >= marker.startLineNumber &&
            position.lineNumber <= marker.endLineNumber &&
            position.column >= marker.startColumn &&
            position.column <= marker.endColumn
          );
          if (clickedMarker) {
            onMarkerClick(clickedMarker);
          }
        }
      });
    }

    // 注册自定义命令
    editor.addCommand(monacoInstance.KeyMod.CtrlCmd | monacoInstance.KeyCode.KeyF, () => {
      if (onFormat) {
        onFormat();
      }
    });
  }, [onCursorPositionChange, onMarkerClick, markers, onFormat]);

  // 处理markers更新
  useEffect(() => {
    if (editorRef.current && monacoRef.current && markers) {
      const model = editorRef.current.getModel();
      if (model) {
        const monacoMarkers = markers.map(marker => ({
          startLineNumber: marker.startLineNumber,
          startColumn: marker.startColumn,
          endLineNumber: marker.endLineNumber,
          endColumn: marker.endColumn,
          message: marker.message,
          severity: marker.severity === 'error' ? monacoRef.current!.MarkerSeverity.Error : 
                   marker.severity === 'warning' ? monacoRef.current!.MarkerSeverity.Warning : 
                   marker.severity === 'info' ? monacoRef.current!.MarkerSeverity.Info :
                   monacoRef.current!.MarkerSeverity.Hint,
          source: marker.source || 'sqlcheck'
        }));
        
        monacoRef.current.editor.setModelMarkers(model, 'sqlcheck', monacoMarkers);
      }
    }
  }, [markers]);

  // 跳转到指定行
  const jumpToLine = useCallback((lineNumber: number, columnNumber?: number) => {
    if (editorRef.current) {
      const position = { lineNumber, column: columnNumber || 1 };
      editorRef.current.setPosition(position);
      editorRef.current.revealLineInCenter(lineNumber);
      editorRef.current.focus();
    }
  }, []);

  // 格式化代码
  const formatCode = useCallback(() => {
    if (editorRef.current) {
      editorRef.current.trigger('format', 'editor.action.formatDocument', {});
    }
  }, []);

  // 全屏切换
  const toggleFullscreen = useCallback(() => {
    // 实现全屏功能
    console.log('Toggle fullscreen');
  }, []);

  // 编辑器配置
  const editorOptions = {
    selectOnLineNumbers: true,
    roundedSelection: false,
    readOnly,
    cursorStyle: 'line',
    automaticLayout: true,
    lineNumbers: showLineNumbers ? 'on' : 'off',
    glyphMargin: true,
    folding: true,
    lineDecorationsWidth: 10,
    lineNumbersMinChars: 3,
    renderLineHighlight: 'all',
    scrollBeyondLastLine: false,
    minimap: { enabled: height > 300 },
    fontSize: 14,
    fontFamily: 'Monaco, Menlo, "Ubuntu Mono", monospace',
    tabSize: 2,
    wordWrap: 'on',
    suggest: {
      showKeywords: true,
      showSnippets: true,
      showFunctions: true
    },
    quickSuggestions: {
      other: true,
      comments: false,
      strings: false
    },
    ...options
  };

  // 计算统计信息
  const issueCount = markers.length;
  const errorCount = markers.filter(m => m.severity === 'error').length;
  const warningCount = markers.filter(m => m.severity === 'warning').length;

  const toolbarItems = [
    {
      key: 'format',
      label: '格式化 (Ctrl+F)',
      icon: <FormatPainterOutlined />,
      onClick: enableFormatting ? (onFormat || formatCode) : undefined,
      disabled: !enableFormatting || readOnly
    },
    {
      key: 'fullscreen',
      label: '全屏',
      icon: <FullscreenOutlined />,
      onClick: toggleFullscreen
    },
    {
      key: 'settings',
      label: '设置',
      icon: <SettingOutlined />,
      onClick: () => console.log('Settings')
    }
  ];

  return (
    <Card 
      className="sql-editor-container"
      style={{ height: height + 80 }}
      title={
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <Space>
            <span>SQL编辑器</span>
            {issueCount > 0 && (
              <Space size={4}>
                {errorCount > 0 && (
                  <Tooltip title={`${errorCount} 个错误`}>
                    <span style={{ color: '#ff4d4f', fontSize: '12px' }}>
                      <BugOutlined /> {errorCount}
                    </span>
                  </Tooltip>
                )}
                {warningCount > 0 && (
                  <Tooltip title={`${warningCount} 个警告`}>
                    <span style={{ color: '#faad14', fontSize: '12px' }}>
                      ⚠ {warningCount}
                    </span>
                  </Tooltip>
                )}
              </Space>
            )}
            {issueCount === 0 && value.trim() && (
              <Tooltip title="没有发现问题">
                <span style={{ color: '#52c41a', fontSize: '12px' }}>
                  <CheckCircleOutlined />
                </span>
              </Tooltip>
            )}
          </Space>
          <Space size={4}>
            {toolbarItems.map(item => (
              <Tooltip key={item.key} title={item.label}>
                <Button
                  type="text"
                  size="small"
                  icon={item.icon}
                  onClick={item.onClick}
                  disabled={item.disabled}
                />
              </Tooltip>
            ))}
          </Space>
        </div>
      }
      bodyStyle={{ padding: 0 }}
    >
      <Editor
        height={height}
        language={language}
        theme={theme}
        value={value}
        onChange={(newValue) => onChange(newValue || '')}
        onMount={handleEditorDidMount}
        options={editorOptions}
      />
    </Card>
  );
};

// 导出工具函数
export const createEditorMarker = (
  issue: {
    lineNumber: number;
    columnNumber: number;
    description: string;
    severity: 'HIGH' | 'MEDIUM' | 'LOW' | 'INFO';
    analysisSource?: 'RULE' | 'LLM';
    id: string;
  }
): EditorMarker => {
  const severityMap = {
    'HIGH': 'error',
    'MEDIUM': 'warning', 
    'LOW': 'info',
    'INFO': 'hint'
  } as const;

  return {
    id: issue.id,
    startLineNumber: issue.lineNumber,
    startColumn: issue.columnNumber,
    endLineNumber: issue.lineNumber,
    endColumn: issue.columnNumber + 10, // 假设问题长度
    message: issue.description,
    severity: severityMap[issue.severity],
    className: `marker-${issue.severity.toLowerCase()}`,
    source: issue.analysisSource?.toLowerCase() as 'rule' | 'llm',
    issueId: issue.id
  };
};

export default SqlEditor;